<?php

namespace ApiBundle\Controller;

use FOS\RestBundle\Controller\FOSRestController;
use GamesBundle\Services\YunxinServer;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * @author  coffey   <coffey@nligo.com>
 *
 * 封装常用方法
 * Class BaseController
 * @package ApiBundle\Controller
 */
class BaseController extends FOSRestController
{
    const API_KEY = 'f0fa2cc1737278f6715a1e5a6ece78804d9c2653';
    public function __construct()
    {
        $this->checkApiKey();
    }

    /**
     * @author  coffey
     *
     * 获取云信操作
     * @return YunxinServer
     */
    public function getYunXinOper()
    {
        $yunxinAppKey = $this->getParameter('yunxin_app_key');
        $yunxinAppSecret = $this->getParameter('yunxin_app_secret');
        return new YunxinServer($yunxinAppKey,$yunxinAppSecret);
    }

    public function checkApiKey()
    {
        $apiKey = isset($_POST['apikey']) ? $_POST['apikey'] : '';
        if($apiKey != self::API_KEY)
        {
            echo new JsonResponse(array('code'=>2,'msg'=>'访问受限','data'=>array()));exit;
        }
    }

    /**
     * @author  coffey
     *
     * 获取em方法
     * @return \Doctrine\Common\Persistence\ObjectManager|object
     */
    public function _em()
    {
        $em = $this->getDoctrine()->getManager();
        return $em;

    }

    /**
     * @author  coffey
     * @param $code 0是成功，1是参数不全或错误，2没有权限，3服务器错误,4未登录,5系统错误,6未查询到数据，7token 过期 8为密码错误
     * @param $msg  填写要返回的信息
     * @param $data  填写要返回的数据
     * @return JsonResponse
     */
    public function FinalJson($code , $data='',$msg='')
    {
        switch ($code) {
            case 0:
                return new JsonResponse(["code" => 0,"msg" => "执行成功","data" => $data], 200,['Access-Control-Allow-Origin'=>'*','Access-Control-Allow-Headers'=>'Content-Type']);
                break;
            case 1:
                return new JsonResponse(["code" => 1,"msg" => "参数不全或错误","data" => $data], 200,['Access-Control-Allow-Origin'=>'*','Access-Control-Allow-Headers'=>'Content-Type']);
                break;
            case 2:
                return new JsonResponse(["code" => 2,"msg" => "没有权限","data" => $data], 200,['Access-Control-Allow-Origin'=>'*','Access-Control-Allow-Headers'=>'Content-Type']);
                break;
            case 3:
                return new JsonResponse(["code" => 3,"msg" => "服务器错误","data" => $data], 500,['Access-Control-Allow-Origin'=>'*','Access-Control-Allow-Headers'=>'Content-Type']);
                break;
            case 4:
                return new JsonResponse(["code" => 4,"msg" => "未登录","data" => $data], 200,['Access-Control-Allow-Origin'=>'*','Access-Control-Allow-Headers'=>'Content-Type']);
                break;
            case 5:
                return new JsonResponse(["code" => 5,"msg" => "系统错误","data" => $data], 200,['Access-Control-Allow-Origin'=>'*','Access-Control-Allow-Headers'=>'Content-Type']);
                break;
            case 6:
                return new JsonResponse(["code" => 6,"msg" => "未查询到数据","data" => $data], 200,['Access-Control-Allow-Origin'=>'*','Access-Control-Allow-Headers'=>'Content-Type']);
                break;
            case 7:
                return new JsonResponse(["code" => 7,"msg" => "token过期","data" => $data], 200,['Access-Control-Allow-Origin'=>'*','Access-Control-Allow-Headers'=>'Content-Type']);
                break;
            case 8:
                return new JsonResponse(["code" => 8,"msg" => "密码错误","data" => $data], 200,['Access-Control-Allow-Origin'=>'*','Access-Control-Allow-Headers'=>'Content-Type']);
                break;
        }
    }

    /**
     * @author  coffey
     * 效验字符串是否为空
     * @param $paramName
     */
    public function checkParam($paramArray = array())
    {
        if(in_array(0,array_map(create_function('&$v','return empty($v)?0:1;'),$paramArray)))
        {
            return false;
        }
        return true;
    }


    public function checkLogin($username)
    {
        $result = $this->get('security.authorization_checker')->isGranted('ROLE_USER');
        if ($result === true) {
            $session_name = $this->getUser()->getuserName();
        }
        if (!empty($session_name)) {
            if ($session_name == $username && $result === true) {
                return $result;
            } else {
                return false;
            }
        } else {
            return false;
        }
        return true;
    }


    /**
     * @author  coffey
     * 用户得到是否登录并返回token的基础方法
     * retrun json
     **/
    public function getLogin()
    {
        $login = $this->get('security.authorization_checker')->isGranted('ROLE_USER');
        $data = array('code'=>'-1','userinfo'=>array());
        if(isset($login) && !empty($login) && $login == true)
        {
            $session_name = $this->getUser()->getuserName();
            if(isset($session_name) && !empty($session_name))
            {
                $user = $this->getUserRepository()->findOneBy(array('username'=>$session_name));
                if(isset($user) && !empty($user))
                {
                    $returnArray = array();
                    $returnArray['userId'] = $user->getId() ? $user->getId() : '';
                    $returnArray['userName'] = $user->getUsername() ? $user->getUsername() : '';
                    $returnArray['email'] = $user->getEmail() ? $user->getEmail() : '';
                    $returnArray['isFull'] = $user->getIsFull() ? $user->getIsFull() : '0';
                    $returnArray['userScore'] = $user->getUserTotalScore() ? $user->getUserTotalScore() : '0.00';
                    $returnArray['safeScore'] = $user->getSafeTotalScore() ? $user->getSafeTotalScore() : '0.00';
                    $returnArray['roles'] = $user->getRoles() ? $user->getRoles() : '';
                    $returnArray['phoneNum'] = $user->getProfile()->getPhoneNum() ? $user->getProfile()->getPhoneNum() : '';
                    $returnArray['wechatNum'] = $user->getProfile()->getWechatNum() ? $user->getProfile()->getWechatNum() : '';
                    $returnArray['alipayNum'] = $user->getProfile()->getAlipayNum() ? $user->getProfile()->getAlipayNum() : '';
                    $returnArray['bankNum'] = $user->getProfile()->getBankNum() ? $user->getProfile()->getBankNum() : '';
                    $returnArray['qqNum'] = $user->getProfile()->getQqNum() ? $user->getProfile()->getQqNum() : '';
                    $returnArray['yunxinId'] = $user->getYunxinId() ? $user->getYunxinId() : '';
                    $returnArray['yunxinToken'] = $user->getYunxinToken() ? $user->getYunxinToken() : '';
                    $tokenData= $this->getToken($returnArray['userName']);
                    $data = $tokenData->getContent();
                    $data = json_decode($data, true);
                    $code = $data['code'];
                    $token = $data['data'];
                    if($code == 0){
                        $returnArray['token'] = $token;
                    }
                    $data ['userinfo']=$returnArray;
                    $data['code'] = 0;
                }
                else
                {
                    $data['code'] = 7;
                }
            }
            else
            {
                $data['code'] = 4;
            }
        }
        else
        {
            $data['code'] = 4;
        }
        return $this->FinalJson($data['code'],$data['userinfo']);
    }


    /**
     * @author  coffey
     *
     * 生成用户token
     * @param $username
     * @return JsonResponse
     */
    public function getToken($username)
    {
        $token = '';
        //加入用户登录检测方法
        if(empty($username))
        {
            $token = '请传输用户名';
            return $this->FinalJson(1,$token);
        }
        $loginResult = $this->checkLogin($username);
        if($loginResult == false){
            $token = '请登录';
            return $this->FinalJson(4,$token);
        }
        $user = $this->getUserRepository()->findOneBy(array('username'=>$username));
        if(empty($user) || !isset($user))
        {
            $token = '未查询到用户信息';
            return $this->FinalJson(6,$token);
        }
        $app_user_secret = $user->getSalt();
        $time = time();
        $secret = md5($username.$app_user_secret.$time);
        $token = $username."_".$secret."_".$time;
        return $this->FinalJson(0,$token);
    }


    /**
     * @author  coffey
     *
     * 检测用户token
     * @param $data['code'] -1 登录失败 1为登录成功
     * @param $data['errcode'] 1参数不全 5未登录 7用户不存在  11 token已过期
     * @return bool
     */
    public function checkToken($token)
    {
        $data = array('code'=>'-1','userinfo'=>array(),'errcode'=>'1');
        if(isset($token) && !empty($token))
        {
            $array = explode("_",$token);
            if(count($array) == 3){
                $username = $array[0];
                $time = $array[2];
                $user = $this->getUserRepository()->findOneBy(array('username'=>$username));
                if(isset($user) && !empty($user))
                {
                    $loginResult = $this->checkLogin($username);
                    if($loginResult == true){
                        $app_user_secret = $user->getSalt();
                        $secret = md5($username.$app_user_secret.$time);
                        if($array[1] == $secret){
                            $overtime = time();
                            $residueTime = $overtime - $time;
                            if($residueTime <= 7200 ){
                                //校验成功&&拼接数组
                                $returnArray = array();
                                $returnArray['userId'] = $user->getId() ? $user->getId() : '';
                                $returnArray['userName'] = $user->getUsername() ? $user->getUsername() : '';
                                $returnArray['email'] = $user->getEmail() ? $user->getEmail() : '';
                                $returnArray['isFull'] = $user->getIsFull() ? $user->getIsFull() : '0';
                                $returnArray['userScore'] = $user->getUserTotalScore() ? $user->getUserTotalScore() : '0.00';
                                $returnArray['safeScore'] = $user->getSafeTotalScore() ? $user->getSafeTotalScore() : '0.00';
                                $returnArray['roles'] = $user->getRoles() ? $user->getRoles() : '';
                                $returnArray['phoneNum'] = $user->getProfile()->getPhoneNum() ? $user->getProfile()->getPhoneNum() : '';
                                $returnArray['wechatNum'] = $user->getProfile()->getWechatNum() ? $user->getProfile()->getWechatNum() : '';
                                $returnArray['alipayNum'] = $user->getProfile()->getAlipayNum() ? $user->getProfile()->getAlipayNum() : '';
                                $returnArray['bankNum'] = $user->getProfile()->getBankNum() ? $user->getProfile()->getBankNum() : '';
                                $returnArray['qqNum'] = $user->getProfile()->getQqNum() ? $user->getProfile()->getQqNum() : '';
                                $returnArray['yunxinId'] = $user->getYunxinId() ? $user->getYunxinId() : '';
                                $returnArray['yunxinToken'] = $user->getYunxinToken() ? $user->getYunxinToken() : '';
                                $data ['userinfo']=$returnArray;
                                $data['code'] = 1;
                            }else{
                                $data['errcode'] = 7;
                            }
                        }
                        else
                        {
                            $data['errcode'] = 1;
                        }
                    }
                    else
                    {
                        $data['errcode'] = 4;
                    }
                }
                else
                {
                    $data['errcode'] = 4;
                }
            }
        }
        return $data;
    }


    public function getUserRepository()
    {
        return $this->_em()->getRepository('GamesBundle:User');
    }

    public function getGamesRepository()
    {
        return $this->_em()->getRepository('GamesBundle:Games');
    }

    public function getGamesUserOrdrRepository()
    {
        return $this->_em()->getRepository('GamesBundle:GamesUserOrder');
    }

    public function getGamesNperRecordRepository()
    {
        return $this->_em()->getRepository('GamesBundle:GameNperRecord');
    }
}
